package com.qin.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.qin.dao.OrderDao;
import com.qin.entity.Book;
import com.qin.entity.Order;
import com.qin.entity.OrderBook;
import com.qin.entity.Shopping;
import com.qin.entity.User;
import com.qin.service.BookService;
import com.qin.service.OrderService;

import cn.hutool.db.Entity;
import cn.hutool.db.Session;

public class OrderServiceImpl implements OrderService{

	private BookService bookService = new BookServiceImpl();
	private OrderDao orderDao = new OrderDao();
	private ShoppingServiceImpl shoppingService = new ShoppingServiceImpl();
	
	@Override
	public Long insertOrder(Order order) {
		return orderDao.insertOrder(order);
	}

	@Override
	public int logicDeleteOrder(Long id) {
		return orderDao.logicDeleteOrder(id);
	}

	@Override
	public Order queryOrderById(Long id) {
		return orderDao.queryOrderById(id);
	}
	
	@Override
	public List<Order> querryOrdersByUserId(Long id) {
		return orderDao.queryOrdersByUserId(id);
	}

	@Override
	public Long insertOrderBeforOrderBookByTx(User user, List<OrderBook> orderbooks) {
		// 拿到session
		Session session = Session.create();
		
		// 开启事务
		try {
		    session.beginTransaction();
		    
		    // 先拿到总价格
		    double priceSum = orderbooks.stream().mapToDouble(OrderBook::getBookPrice).sum();
		    // 得到购物车的图书id 
		    List<Shopping> shoppingItemsByUserId = shoppingService.getShoppingItemsByUserId(user.getId());
		    // 拿到购物车中要清理的图书分类id
		    Map<Long, Integer> collect2 = orderbooks.stream().collect(Collectors.toMap(OrderBook::getBookId, OrderBook::getBookNum));
		    
		    // 插入一条订单信息
		    Order order = new Order();
		    order.setUserName(user.getName());
			order.setUserId(user.getId());
			order.setPrice(priceSum);
			
			// 得到一个自增主键
			Long insertForGeneratedKey = session.insertForGeneratedKey(Entity.parse(order, true, true));
			
			// 遍历订单图书，设置自增主键，然后转换成entity
			List<Entity> collect = orderbooks.stream().map(orderBook->{
				// 给每本订单图书都设置订单id
				orderBook.setOrderId(insertForGeneratedKey);
				
				// 查询图书设置属性
				Book bookById = bookService.getBookById(orderBook.getBookId());
				// 设置价格
				orderBook.setBookPrice(bookById.getPrice());
				// 设置折扣
				orderBook.setBookDiscount(bookById.getDiscount());
				
				return Entity.parse(orderBook, true, true);
			}).collect(Collectors.toList());
			
			// 遍历购物车，观察是否需要删除
			shoppingItemsByUserId.stream().forEach(shopping->{
				if(collect2.containsKey(shopping.getBookId())) {
					// 拿到当前订单里要求的数量
					Integer bookNumByOrder = collect2.get(shopping.getBookId());
					// 拿到购物车里已有的数量
					Integer bookNumByShopping = shopping.getBookNum();
					
					// 如果小于购物车里面的图书数量，设置变化的数量
					if(bookNumByOrder < bookNumByShopping) {
						try {
							String sql = "UPDATE `shopping` SET `book_num` = `book_num` - ? WHERE `id` = ?";
							// 执行sql语句
							session.execute(sql,bookNumByOrder,shopping.getId());
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}else{
						// 其他任何情况都是清空
						try {
							String sql = "UPDATE `shopping` SET `status` =  0 WHERE `id` = ?";
							// 执行sql语句
							session.execute(sql, shopping.getId());
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			});
			
			// 批量插入
			session.insert(collect);

		    session.commit();
		    // 插入成功！！
		    return insertForGeneratedKey;
		} catch (SQLException e) {
		    session.quietRollback();
		}
		return null;
	}


}
